package gang.org.springframework.framework.util;
import gang.org.springframework.framework.io.GangResourceLoader;
import gang.org.springframework.framework.bean.GangBeanUtils;
import gang.org.springframework.framework.factory.GangAware;
import gang.org.springframework.framework.factory.GangBeanClassLoaderAware;
import gang.org.springframework.framework.support.GangBeanDefinitionRegistry;
/**
 * @author gang.chen
 * @description
 * @Date 2021/7/27 12:52
 */
public class GangParserStrategyUtils {

    //TODO
    public static <T> T instantiateClass(Class<?> clazz,
                                         Class<T> assignableTo,
                                         Object environment,
                                         Object resourceLoader,
                                         GangBeanDefinitionRegistry registry){

        //TODO
        ClassLoader classLoader = registry.getClass().getClassLoader();
        T instance = (T) createInstance(clazz,null,null,registry,classLoader);
        GangParserStrategyUtils.invokeAwareMethods(instance,null,null,registry,classLoader);
        return instance;
    }

    private static Object createInstance(Class<?> clazz,
                                         Object environment,
                                         GangResourceLoader resourceLoader,
                                         GangBeanDefinitionRegistry registry,
                                         ClassLoader classLoader
    )
    {
        //TODO 构造函数初始化类属性
        return GangBeanUtils.instantiateClass(clazz);
    }

    /**
     * TODO
     * 业务意义：对初始化实例进行属性赋值
     * @param parserStrategyBean {@link gang.org.springframework.boot.autoconfigure.GangAutoConfigurationImportSelector}
     * */
    private static void invokeAwareMethods(Object parserStrategyBean,
                                           Object environment,
                                           GangResourceLoader resourceLoader,
                                           GangBeanDefinitionRegistry registry,
                                           ClassLoader classLoader){
        if (parserStrategyBean instanceof GangAware) {

            if (parserStrategyBean instanceof GangBeanClassLoaderAware && classLoader != null) {
                ((GangBeanClassLoaderAware)parserStrategyBean).setBeanClassLoader(classLoader);
            }

        }
    }
}
